import {Request, Response, NextFunction} from "express";
import Session = Express.Session;
import Region from './act.region';
import PWSApp from '../../core/app';
import HomeAction from './act.home';
import UserAction from './act.user';
import CartAction from './act.cart';
import OrderAction from './act.order';
import AddrAction from './act.address';
import CenterAction from './act.center';
import CouponAction from './act.coupon';
import FavoriteAction from './act.favorite';

import {Magics} from "../../core/magics";
import * as utils from '../../core/utils';
import ProductAction from './act.product';
import BaseLoader from '../../core/base.loader';

class ApiLoader extends BaseLoader {

    constructor(app: PWSApp) {
        super(app);
    }

    protected _load() {
        new Region(this.app);
        new HomeAction(this.app);
        new ProductAction(this.app);

        new UserAction(this.app);
        new CartAction(this.app);
        new AddrAction(this.app);
        new OrderAction(this.app);
        new CouponAction(this.app);
        new CenterAction(this.app);
        new FavoriteAction(this.app);
    }

    protected  _checkLogin(): void {
        let needLogin = new RegExp('^/api/(center|favor|coupon|cart|addr|order|product)(/?.*)');
        this.app.registerRoutes(needLogin, (req: Request, res: Response, next: NextFunction) => {
            if(!req.session[Magics.SessUser]){
                req.session[Magics.SessUser] = {};
                req.session[Magics.SessUser]['_id'] = '5881848fd2b9a7042a38d820';
            }
            if( !this._isLogin(req.session) ){
                res.redirect('/login');
                return;
            }
            next();
        });
    }

    protected _isLogin(sess: Session): boolean {
        return !!(sess && sess[Magics.SessUser] && utils.isObjectId(sess[Magics.SessUser]._id));
    }
}

export = function(app: PWSApp) {
    new ApiLoader(app);
}
